package com.example.yangxu0703.thundermapclient.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.BaseAdapter;
import android.widget.ListView;

import com.amap.api.location.APSService;
import com.example.yangxu0703.thundermapclient.R;
import com.example.yangxu0703.thundermapclient.iterface.ApkCallback;
import com.example.yangxu0703.thundermapclient.util.Util;
import com.facebook.drawee.view.SimpleDraweeView;
import com.thundersoft.mm.phone.ConnectionManager;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import static com.thundersoft.mm.phone.ConnectionManager.SEND_APK;

@SuppressLint("NewApi")
public class SendApkActivity extends Activity implements View.OnClickListener {

    private static final String TAG = "MainActivity";
    private ListView appList;
    private ArrayList<ResolveInfo> mApps;
    private PackageManager pm;
    private MyAdapter adapter;
    private Dialog dialog;
    TextView textView = null;
    ProgressBar progressBar = null;
    private SharedPreferences sharedPreferences;
    private List<ResolveInfo> Restore = new ArrayList<>();
    private TextView arrback, choice;
    private int APKStatus[];
    private String path = "/sdcard/ARlauncher/cache/";
    private ArrayList<Boolean> mode = new ArrayList<>();
    private String sendString="";
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (ConnectionManager.btTextMsgListener.connected) {
                        if (ConnectionManager.mGlassesIp != null) {
                            dialog.show();
                        } else {
                            ConnectionManager.wifiConnection.init(ConnectionManager.mContext);
                            Toast.makeText(SendApkActivity.this, "WIFIp2p正在连接请稍后重试！", Toast.LENGTH_SHORT).show();
                        }

                    } else {
                        MediaCenterActivity.ReconnectBT();
                        Toast.makeText(SendApkActivity.this, "蓝牙正在连接稍后重试！", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 2:
                    /* textView.setText(msg.getData().getString("正在送中..."));*/
                    progressBar.setProgress(msg.arg1);
                    if (msg.arg1 == 100 && dialog.isShowing()) {
                        dialog.dismiss();
                        SendApkActivity.this.finish();
                    }
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_apk);
        sharedPreferences = getSharedPreferences("AreadySendAPK", MODE_PRIVATE);
        pm = getPackageManager();
        appList = (ListView) findViewById(R.id.appGridView);
        arrback = findViewById(R.id.back_share);
        arrback.setOnClickListener(this);
        choice = findViewById(R.id.send_action);
        choice.setOnClickListener(this);
        mode.add(0, false);
        ConnectionManager.wifiConnection.init(ConnectionManager.mContext);
        MediaCenterActivity.ReconnectBT();
        sendString=sharedPreferences.getString("AreadySendAPK","");

        initApp();
        clearArray(sendString);
        adapter = new MyAdapter(this, mApps, APKStatus, mode);
        appList.setAdapter(adapter);
        appList.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                /*  handler.sendEmptyMessage(1);*/
                final ResolveInfo app = mApps.get(position);
                if (APKStatus[position] != 1) {
                    APKStatus[position] = 1;
                    Restore.add(app);
                } else {
                    APKStatus[position] = 0;
                    Restore.remove(app);
                }
                adapter.notifyDataSetChanged();

            }

        });
        initDialog();
    }


    private void SendAPk(final ResolveInfo app) throws FileNotFoundException {
        final CharSequence appName = app.loadLabel(pm);
        sendString=sendString+"@"+appName;
        sharedPreferences.edit().putString("AreadySendAPK",sendString);
        String appDir = null;
        String name = null;

        try {
            appDir = getPackageManager().getApplicationInfo(app.activityInfo.packageName, 0).sourceDir;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }

        if (appDir != null) {
            ConnectionManager.sendFile(new File(appDir), SEND_APK, new ApkCallback() {
                @Override
                public void fallBackProgress(int pro) {
                    int i = 0;
                    if (pro == -1) {
                        Restore.remove(app);
                        Toast.makeText(SendApkActivity.this, "发送失败！", Toast.LENGTH_SHORT).show();
                    } else {
                        Log.i(TAG, "progress------" + pro);
                        if (pro == 100) {
                            i = 1;
                            Message message = new Message();
                            message.arg1 = i / Restore.size();
                            message.what = 2;
                            handler.sendMessage(message);
                        }
                    }
                }
            });
        } else {
            Toast.makeText(SendApkActivity.this, "找不到安装包", Toast.LENGTH_SHORT).show();
        }

    }

    private void clearArray(String sendString) {
        APKStatus = new int[mApps.size()];
        String temArry[] =sendString.split("@");
        for (int i = 0; i < mApps.size(); i++) {
            for (int j=0;j<temArry.length;j++){
                    if (mApps.get(i).loadLabel(pm).equals(temArry[j])){
                        APKStatus[i] = 1;
                        break;
                    }else {
                        APKStatus[i] = 0;
                    }
            }

        }

    }

    private void initDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(SendApkActivity.this);
        View dialogview = LayoutInflater.from(SendApkActivity.this).inflate(R.layout.dialog_send_apk, null, false);
        textView = dialogview.findViewById(R.id.name_apk);
        progressBar = dialogview.findViewById(R.id.apk_send_pro);
        builder.setView(dialogview);
        dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
    }

    /**
     * 初始化app列表
     */
    private void initApp() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        mApps = (ArrayList<ResolveInfo>) pm.queryIntentActivities(intent, 0);
        Collections.sort(mApps, new Comparator<ResolveInfo>() {
            @Override
            public int compare(ResolveInfo a, ResolveInfo b) {
                PackageManager pm = getPackageManager();
                return String.CASE_INSENSITIVE_ORDER.compare(a.loadLabel(pm).toString(), b.loadLabel(pm).toString());
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send_action:
                if (mode.get(0)) {
                    Log.i(TAG,"send");
                    choice.setText("选择");
                    mode.remove(0);
                    mode.add(0,false);
                    adapter.notifyDataSetChanged();
                    handler.sendEmptyMessage(1);
                    for (ResolveInfo info : Restore) {
                        try {
                            SendAPk(info);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    Log.i(TAG,"choose");
                    mode.remove(0);
                    mode.add(0,true);
                    adapter.notifyDataSetChanged();
                    choice.setText("发送");
                }
                break;
            case R.id.back_share:
                ConnectionManager.stopWifiP2p();
                ConnectionManager.wifiConnection.release();
                SendApkActivity.this.finish();
                break;
        }
    }

    private class MyAdapter extends BaseAdapter {

        private ArrayList<ResolveInfo> arrayList;
        private Context context;
        private int[] APKStatus;
        private ArrayList<Boolean> mode;

        public MyAdapter(Context context, ArrayList<ResolveInfo> arrayList, int[] APKStatus, ArrayList<Boolean> mode) {
            this.context = context;
            this.arrayList = arrayList;
            this.APKStatus = APKStatus;
            this.mode = mode;
        }

        @Override
        public int getCount() {
            return arrayList.size();
        }

        @Override
        public Object getItem(int position) {
            return arrayList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.item_gridview, null);
                holder = new ViewHolder();
                holder.appImageView = (SimpleDraweeView) convertView.findViewById(R.id.appImageView);
                holder.appNameTextView = (TextView) convertView.findViewById(R.id.appNameTextView);
                holder.APKStatus = convertView.findViewById(R.id.choose_status);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            Log.i(TAG,"msg-----"+mode.get(0));
            if (mode.get(0)) {
                if (APKStatus[position] == 1) {
                    holder.APKStatus.setBackground(context.getResources().getDrawable(R.drawable.choosed_icon));
                } else {
                    holder.APKStatus.setBackground(context.getResources().getDrawable(R.drawable.cycle));
                }
            } else {
                if (APKStatus[position] == 1) {
                    holder.APKStatus.setBackground(context.getResources().getDrawable(R.drawable.choosed_icon));
                }else {
                    holder.APKStatus.setBackground(null);
                }
            }

            ResolveInfo app = mApps.get(position);
            CharSequence appName = app.loadLabel(pm);
            holder.appNameTextView.setText(appName);
            Drawable appIcon = app.loadIcon(pm);
            holder.appImageView.setImageDrawable(appIcon);
            return convertView;
        }

        private class ViewHolder {
            public SimpleDraweeView appImageView;
            public TextView appNameTextView, APKStatus;
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        ConnectionManager.stopWifiP2p();
        ConnectionManager.wifiConnection.release();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ConnectionManager.stopWifiP2p();
        ConnectionManager.wifiConnection.release();
    }
}